import axios from 'axios'
import {Toast} from 'vant'
import router from '../router/index'
import {setLocal} from '../common/js/ustil'
console.log(router, 123456);
axios.defaults.baseURL = '//backend-api-01.newbee.ltd/api/v1'  // 后端地址
// 只要用axios进行接口请求的，都可以在请求头里面携带cookie和credentials，即用户凭证，是指 cookie、HTTP身份验证和TLS客户端证书
axios.defaults.withCredentials = true 
axios.defaults.headers['X-requested-With'] = 'XMLHttpRequest'
axios.defaults.headers['token'] = localStorage.getItem('token') || ''
axios.defaults.headers.post['Content-Type'] = 'application/json'  // 请求格式json

axios.interceptors.response.use(res => {
   if(typeof res.data !== 'object') { // 返回的不是对象
    Toast.fail('服务端异常')
    return Promise.reject(res) // catcch这个res
   }

   if (res.data.resultCode != 200) { 
    if (res.data.message) Toast.fail(res.data.message)
    if (res.data.resultCode == 416 && router.currentRoute.value.path !== '/home' && router.currentRoute.value.path !== '/catory') { // 登录超时
        router.push({ path: '/login' })
    }

     
    if (res.data.data && router.currentRoute.value.path == '/login') {
        setLocal('token', res.data.data)
        axios.defaults.headers['token'] = res.data.data
      }

    return Promise.reject(res.data)
   }

   return res.data
})


export default axios